<template>
  <div class="regist-box">
    <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
    >
      <div style="font-weight: bold;color: aliceblue">
        <el-form-item prop="name">
          <el-input placeholder="输入用户名" v-model="ruleForm.name" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="pass">
          <el-input placeholder="输入密码" v-model="ruleForm.pass" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="checkPass">
          <el-input placeholder="重复密码" v-model="ruleForm.checkPass" type="password" autocomplete="off" />
        </el-form-item>
      </div>
      <div class="form-actions" style="display: flex; justify-content: space-between;">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交表单
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          重置数据
        </el-button>
        <el-button type="warning" @click="doLogin">
          返回登陆
        </el-button>
      </div>
    </el-form>
  </div>
</template>


<script lang="ts" setup>
import { reactive, ref } from 'vue'
import {ElMessage, type FormInstance, type FormRules} from 'element-plus'
import {postUser, checkName} from "@/api/api";
import {useRouter} from "vue-router";

const ruleFormRef = ref<FormInstance>()
const router = useRouter()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不可为空'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass')
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("两次密码不一致"))
  } else {
    callback()
  }
}
const validateName = (rule: any, value: string, callback: (error?: Error) => void) => {
  (async () => {
    try {
      if (value === '') {
        callback(new Error('用户名不可以为空'));
      } else {
        const regex = /^[a-zA-Z0-9]+$/;
        if (!regex.test(value)) {
          callback(new Error('用户名只可以包含数字和字母'));
        } else {
          const isRepeated = await check_repete_name(value);
          if (isRepeated) {
            callback(new Error('用户名不可以重复'));
          } else {
            callback();
          }
        }
      }
    } catch (e) {
      callback(new Error('验证过程中发生错误'));
    }
  })();
};
async function check_repete_name(value: string): Promise<any> {
  try {
    return await checkName(value); // 确保 checkName 是一个有效的异步函数
  } catch (e) {
    console.error(e);
  }
}

const ruleForm = reactive({
  name:'',
  pass: '',
  checkPass: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  name: [{validator: validateName, trigger: 'blur'}],
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      submit()
      ElMessage({
        type: 'warning',
        message: `注册成功`,
      });
    } else {
      console.log('error submit!')
    }
  })
}
async function submit() {
  try {
    await postUser(ruleForm.name,ruleForm.pass)
  }catch (e) {
    console.log(e)
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  ElMessage({
    type: 'warning',
    message: `重置成功`,
  });
}

function doLogin() {
  router.replace("/")
  ElMessage({
    type: 'info',
    message: `欢迎来到登录界面`,
  });
}

</script>

<style scoped>
.regist-box {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 500px;
  padding: 40px;
  transform: translate(-50%, -50%);
  background-color: darkslategrey;
  box-sizing: border-box;
  box-shadow: 0 15px 25px rgba(0, 0, 0, .6);
  border-radius: 10px;
}
</style>